package com.infodeli.user.login.controller;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.infodeli.common.exception.ExceptionEnum;
import com.infodeli.common.exception.LoginException;
import com.infodeli.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import com.infodeli.user.login.entity.UserEntity;
import com.infodeli.user.login.service.UserService;
import sun.reflect.annotation.ExceptionProxy;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 
 *
 * @author zzs
 * @email zzs@infodeli.com
 * @date 2021-04-12 19:36:06
 */
@RestController
@RequestMapping("login/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录：登录验证，生成token【用户占领】
     */
    @PostMapping("dologin")
    public R doLogin(@RequestBody UserEntity user){
        System.out.println("后台收到登录信息" + user);
        UserEntity one = null;
        String token = null;
        try{
            // todo: @ControllerAdviser 统一的异常处理
            one = userService.doLogin(user);
            // 登录成功，生成JWT
            Map<String, String> userMap = userService.getUserMap(one);
            token = JWTUtils.getToken(userMap);
        }catch(LoginException e){
            return R.error(e.getCode(), e.getMsg());
        }catch(UnsupportedEncodingException e){
            return R.error(e.getMessage());
        }

        // 登录成功
        return R.ok().put("user", one).put("code",10000).put("token", token);
    }

    /**
     * 注册：绑定邮箱【用户暂时占领】
     * stuid、password、nickName
     */
    @PostMapping("/register")
    public R register(@RequestBody UserEntity user){
        userService.register(user);
        return R.ok();
    }

    // 最初的session方案【弃用】
    @PostMapping("/session/user")
    public R afterLogin(HttpSession session){
        UserEntity user = (UserEntity) session.getAttribute("user");

        return R.ok().put("session_user",user);
    }

    /**
     * 登出：【用户占领】
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        UserEntity user = (UserEntity)session.getAttribute("user");
        session.removeAttribute("user");
        System.out.println("退出系统"+user);
        return R.ok();
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("login:user:list")
    public R list(@RequestBody Map<String, Object> params){
        PageUtils page = userService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息：【用户占领】
     */
    @RequestMapping("/info")
    //@RequiresPermissions("login:user:info")
    public R info(HttpServletRequest request) throws UnsupportedEncodingException {
        String uid = JWTUtils.getTokenInfo(request.getHeader("token"), "uid");

        UserEntity user = userService.getById(uid);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("login:user:save")
    public R save(@RequestBody UserEntity user){
		userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("login:user:update")
    public R update(@RequestBody UserEntity user){
        String password = user.getPassword();
        if(password != null){
            if(password.length()<6){
                throw ServiceExceptionUtils.getServiceException(ExceptionEnum.PASSWORD_MIN_SIX);
            }else{
                user.setPassword(ComTool.getMd5Str(password));
            }
        }
        userService.updateById(user);

        return R.ok();
    }

    /**
     * 重置密码：【管理员占领】【代废弃：复用上面update】
     */
    @PostMapping("/update/reset/password/{uid}")
    public R updateResetPassword(@PathVariable("uid")Long uid){
        UserEntity user = new UserEntity();
        user.setUid(uid);
        user.setPassword(ComTool.getMd5Str("123456"));
        userService.updateById(user);
        return R.ok();
    }



    /**
     * 封禁用户
     */
    @PostMapping("/update/{uid}/{freeTime}")
    public R updateFreeTime(@PathVariable("uid")Long uid, @PathVariable("freeTime")String freeTime){
        UserEntity user = new UserEntity();
        user.setUid(uid);
        user.setUserStatus(0);
        user.setFreeTime(freeTime);
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("login:user:delete")
    public R delete(@RequestBody Long[] uids){
		userService.removeByIds(Arrays.asList(uids));

        return R.ok();
    }


}
